<?php
/**
 * Created by PhpStorm.
 * User: yuesir
 * Date: 2017/6/4
 * Time: 上午12:05
 */

namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\model\User as UserModel;
use app\api\service\Token as TokenService;
use app\api\validate\AddressNew;
use app\lib\exception\SuccessMessage;
use app\lib\exception\UserException;

class Address extends BaseController
{
    protected $beforeActionList = [
        'checkPrimaryScope' => ['only' => 'createOrUpdate']
    ];

    /**
     * 创建或者更新基类
     * @return \think\response\Json
     * @throws UserException
     * @throws \app\lib\exception\ParameterException
     * @throws \think\Exception
     */
    public function createOrUpdate()
    {
        $validator = new AddressNew();
        $validator->goCheck();
        
        $uid = TokenService::getUidByToken();
        $user = UserModel::get($uid);
        if ( !$user) {
            throw new UserException();
        }

        //通过 post. 来获取所有的 post 数据
        $addressArr = $validator->getDataByRule(input('post.'));
        if ( !$user->address) {
            $user->address()->save($addressArr);
        } else {
            $user->address->save($addressArr);
        }
        
        return json(new SuccessMessage(), 201);
    }
}